package com.adminserver.controller;

import cn.hutool.core.util.RandomUtil;
import com.adminserver.entity.UserRoleEntity;
import com.adminserver.entity.WorkerEntity;
import com.adminserver.service.UserRoleService;
import com.adminserver.service.WorkerService;
import com.adminserver.util.RedisUtil;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/worker")
public class WorkerController {

    @Autowired
    WorkerService workerService;

    @Autowired
    UserRoleService userRoleService;

    Jedis redis = RedisUtil.getRedis();

    // 添加维修员保存信息前缀
    public static String ADD_WORKER_PREFIX = "add_worker:";

    // 添加维修员邀请码有效时间/秒 (30天)
    public static int ADD_WORKER_EFFECTIVE_TIME = 60 * 60;

    @GetMapping("/pullAllWorker")
    public ResponseUtil pullAllWorker() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(workerService.list());
    }

    @PostMapping("/updateWorker")
    public ResponseUtil updateWorker(@RequestBody WorkerEntity workerEntity) {
        System.out.println(workerEntity);
        workerEntity.setHeadimgurl(null);
        workerEntity.setNickname(null);
        workerEntity.setRegisterTime(null);
        if (workerService.updateById(workerEntity))
            return ResponseUtil.setE(ResponseEnum.OK).setMsg(workerEntity.getWorkerName() + " 信息更新成功");
        else
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("信息更新失败");
    }

    @Transactional
    @PostMapping("/delWorker")
    public ResponseUtil delWorker(@RequestBody WorkerEntity workerEntity) {
        try{
            workerService.removeById(workerEntity.getOpenid());
            LambdaQueryWrapper<UserRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserRoleEntity::getUserId, workerEntity.getOpenid());
            userRoleService.remove(lambdaQueryWrapper);
            return ResponseUtil.setE(ResponseEnum.OK).setMsg(workerEntity.getWorkerName() + " 删除成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg(workerEntity.getWorkerName() + " 删除失败");
        }
    }

    @PostMapping("/addNewWorker")
    public ResponseUtil addNewWorker(@RequestBody WorkerEntity workerEntity) {
        // 6位数 邀请码
        String numbers = RandomUtil.randomNumbers(6);
        workerEntity.setOpenid(numbers);
        redis.setex(WorkerController.ADD_WORKER_PREFIX + numbers,
                WorkerController.ADD_WORKER_EFFECTIVE_TIME,
                JSON.toJSONString(workerEntity));
        return ResponseUtil.setE(ResponseEnum.OK).setMsg("添加维修员 " + workerEntity.getWorkerName() + " 成功，邀请码已生成");
    }

    @PostMapping("/addNewWorkers")
    public ResponseUtil addNewWorker(@RequestBody List<WorkerEntity> workerEntityList) {
        // 6位数 邀请码
        redis.select(0);
        workerEntityList.forEach(item -> {
            String numbers = RandomUtil.randomNumbers(6);
            item.setOpenid(numbers);
            redis.setex(WorkerController.ADD_WORKER_PREFIX + numbers,
                    WorkerController.ADD_WORKER_EFFECTIVE_TIME,
                    JSON.toJSONString(item));
        });
        return ResponseUtil.setE(ResponseEnum.OK).setMsg("添加 " + workerEntityList.size() + " 位维修员成功，邀请码已生成");
    }

    @GetMapping("/pullNewWorkerRegState")
    public ResponseUtil pullNewWorkerRegState() {
        redis.select(0);
        Set<String> keys = redis.keys(ADD_WORKER_PREFIX + "*");
        if (keys.size() == 0) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("暂无待注册数据");
        return ResponseUtil.setE(ResponseEnum.OK).setData(redis.mget(keys.toArray(new String[]{})));
    }
}
